<%-- Form Function --%>
<script type="text/javascript">

    
    $(document).ready(function() {
        $("#txtPhone").mask("999-9999-999");
        $("input, textarea, select, button").uniform();
        $("#btnReset").click(function(){
            $("#formSearch").get(0).reset();
            $("#btnSubmit").attr("disabled",false); flAuto = false; // When has auto search
            $.uniform.update(" input, textarea, select, button");
            return false});

        $("#formSearch").validate({
            submitHandler: function(form) {
                gridReload();
                //$(form).ajaxSubmit();
            }
        });
        var options = {
            target:        '#output1',   // target element(s) to be updated with server response
            beforeSubmit:  showRequest,  // pre-submit callback
            success:       showResponse  // post-submit callback

            // other available options:
            //url:       url         // override for form's 'action' attribute
            //type:      type        // 'get' or 'post', override for form's 'method' attribute
            //dataType:  null        // 'xml', 'script', or 'json' (expected server response type)
            //clearForm: true        // clear all form fields after successful submit
            //resetForm: true        // reset the form after successful submit

            // $.ajax options can be used here too, for example:
            //timeout:   3000
        };

        // bind form using 'ajaxForm'
        $('#formSearch').ajaxForm(options);
    });

    // pre-submit callback
    function showRequest(formData, jqForm, options) {
        // formData is an array; here we use $.param to convert it to a string to display it
        // but the form plugin does this for you automatically when it submits the data
        var queryString = $.param(formData);

        // jqForm is a jQuery object encapsulating the form element.  To access the
        // DOM element for the form do this:
        // var formElement = jqForm[0];

        alert('About to submit: \n\n' + queryString);

        // here we could return false to prevent the form from being submitted;
        // returning anything other than false will allow the form submit to continue
        return true;
    }

    // post-submit callback
    function showResponse(responseText, statusText, xhr, $form)  {
        // for normal html responses, the first argument to the success callback
        // is the XMLHttpRequest object's responseText property

        // if the ajaxForm method was passed an Options Object with the dataType
        // property set to 'xml' then the first argument to the success callback
        // is the XMLHttpRequest object's responseXML property

        // if the ajaxForm method was passed an Options Object with the dataType
        // property set to 'json' then the first argument to the success callback
        // is the json data object returned by the server

        alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
            '\n\nThe output div should have already been updated with the responseText.');
    } 
</script>
<%-- End Form Function --%>

<%-- jQGrid Init --%>
<script type="text/javascript">
    $(function() {
        $("#grid").jqGrid({
            url:'<%=request.getContextPath()%>/jQueryGrid/searchGridData',
            datatype: 'json',
            mtype: 'POST',
            colNames:['Id', 'Product Name', 'Category'],
            colModel:[
                {name:'id',index:'id', width:55,editable:false,editoptions:{readonly:true,size:10},hidden:false},
                {name:'productName',index:'productName', width:100,editable:true,editoptions:{readonly:true,size:10},hidden:false},
                {name:'categoryName',index:'categoryName', width:100,editable:true,editoptions:{readonly:true,size:10},hidden:false}
            ],
            postData: {
            },
            rowNum:20,
            rowList:[20,40,60],
            height: 200,
            autowidth: true,
            rownumbers: true,
            pager: '#pager',
            sortname: 'id',
            viewrecords: true,
            sortorder: "asc",
            caption:"Products",
            emptyrecords: "Empty records",
            loadonce: false,
            loadComplete: function() {
                alert("Complete");
            },
            jsonReader : {
                root: "rows",
                page: "page",
                total: "total",
                records: "records",
                repeatitems: true, //if 'false' will chage json reader format to 'name' require
                //cell: "cell",
                id: "0" //id: "id"
            }
        });
        $("#grid").jqGrid('navGrid','#pager',
        {edit:false,add:false,del:false,search:true},
        { },
        { },
        { },
        {
            sopt:['eq', 'ne', 'lt', 'gt', 'cn', 'bw', 'ew'],
            closeOnEscape: true,
            multipleSearch: true,
            closeAfterSearch: true }
    );



        $("#grid").navButtonAdd('#pager',
        { 	caption:"Add",
            buttonicon:"ui-icon-plus",
            onClickButton: addRow,
            position: "last",
            title:"",
            cursor: "pointer"
        }
    );

        $("#grid").navButtonAdd('#pager',
        { 	caption:"Edit",
            buttonicon:"ui-icon-pencil",
            onClickButton: editRow,
            position: "last",
            title:"",
            cursor: "pointer"
        }
    );

        $("#grid").navButtonAdd('#pager',
        { 	caption:"Delete",
            buttonicon:"ui-icon-trash",
            onClickButton: deleteRow,
            position: "last",
            title:"",
            cursor: "pointer"
        }
    );

        $("#btnFilter").click(function(){
            $("#grid").jqGrid('searchGrid',
            {multipleSearch: false,
                sopt:['eq']}
        );
        });

        // Toolbar Search
        $("#grid").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : true, defaultSearch:"cn"});

    }
);
</script>
<%-- End jQGrid Init --%>

<%-- jQGrid Search Function --%>
<script type="text/javascript">
    var timeoutHnd;
    var flAuto = false;

    function doSearch(ev){
        if(!flAuto)
            return;
        //	var elem = ev.target||ev.srcElement;
        if(timeoutHnd)
            clearTimeout(timeoutHnd)
        timeoutHnd = setTimeout(gridReload,500)
    }

    function gridReload(){
        var txtName_mask = jQuery("#txtName").val();
        jQuery("#grid").jqGrid('setGridParam',{url:"<%=request.getContextPath()%>/jQueryGrid/searchGridData?txtName_mask="+txtName_mask,page:1}).trigger("reloadGrid");
    }
    function enableAutosubmit(state){
        flAuto = state;
        jQuery("#btnSubmit").attr("disabled",flAuto);
        $.uniform.update("#btnSubmit");
    }
</script>
<%-- End jQGrid Search Function --%>

<%-- jQGrid Function --%>
<script type="text/javascript">
    function addRow() {

        // Get the currently selected row
        $("#grid").jqGrid('editGridRow','new',
        { 	url: "jqGridServlet/add",
            editData: {
            },
            recreateForm: true,
            beforeShowForm: function(form) {
            },
            closeAfterAdd: true,
            reloadAfterSubmit:false,
            afterSubmit : function(response, postdata)
            {
                var result = eval('(' + response.responseText + ')');
                var errors = "";

                if (result.success == false) {
                    for (var i = 0; i < result.message.length; i++) {
                        errors +=  result.message[i] + "<br/>";
                    }
                }  else {
                    $("#dialog").text('Entry has been added successfully');
                    $("#dialog").dialog(
                    {	title: 'Success',
                        modal: true,
                        buttons: {"Ok": function()  {
                                $(this).dialog("close");}
                        }
                    });
                }
                // only used for adding new records
                var new_id = null;

                return [result.success, errors, new_id];
            }
        });

    }

    function editRow() {
        // Get the currently selected row
        var row = $("#grid").jqGrid('getGridParam','selrow');

        if( row != null )
            $("#grid").jqGrid('editGridRow',row,
        {	url: "jqGridServlet/edit",
            editData: {
            },
            recreateForm: true,
            beforeShowForm: function(form) {
            },
            closeAfterEdit: true,
            reloadAfterSubmit:false,
            afterSubmit : function(response, postdata)
            {
                var result = eval('(' + response.responseText + ')');
                var errors = "";

                if (result.success == false) {
                    for (var i = 0; i < result.message.length; i++) {
                        errors +=  result.message[i] + "<br/>";
                    }
                }  else {
                    jq("#dialog").text('Entry has been edited successfully');
                    jq("#dialog").dialog(
                    {	title: 'Success',
                        modal: true,
                        buttons: {"Ok": function()  {
                                jq(this).dialog("close");}
                        }
                    });
                }

                return [result.success, errors, null];
            }
        });
        else $( "#dialogSelectRow" ).dialog();
    }

    function deleteRow() {
        // Get the currently selected row
        var row = $("#grid").jqGrid('getGridParam','selrow');

        // A pop-up dialog will appear to confirm the selected action
        if( row != null )
            $("#grid").jqGrid( 'delGridRow', row,
        { url: 'jqGridServlet/delete',
            recreateForm: true,
            beforeShowForm: function(form) {
                //change title
                $(".delmsg").replaceWith('<span style="white-space: pre;">' +
                    'Delete selected record?' + '</span>');

                //hide arrows
                $('#pData').hide();
                $('#nData').hide();
            },
            reloadAfterSubmit:false,
            closeAfterDelete: true,
            afterSubmit : function(response, postdata)
            {
                var result = eval('(' + response.responseText + ')');
                var errors = "";

                if (result.success == false) {
                    for (var i = 0; i < result.message.length; i++) {
                        errors +=  result.message[i] + "<br/>";
                    }
                }  else {
                    $("#dialog").text('Entry has been deleted successfully');
                    $("#dialog").dialog(
                    {	title: 'Success',
                        modal: true,
                        buttons: {"Ok": function()  {
                                $(this).dialog("close");}
                        }
                    });
                }
                // only used for adding new records
                var new_id = null;

                return [result.success, errors, new_id];
            }
        });
        else $( "#dialogSelectRow" ).dialog();
    }

</script>
<%-- End jQGrid Function --%>

<form id="formSearch" action="a.jsp" method="GET">
    <fieldset>
        <legend>Search</legend>
        <table>
            <tr>
                <td>
                    Enable Autosearch
                </td>
                <td>
                    <input type="checkbox" id="chkAutoSearch" onclick="enableAutosubmit(this.checked)">
                </td>
            </tr>
            <tr>
                <td>Enter Name</td>
                <td>
                    <input type="text" name="txtName" id="txtName" class="" value="" onkeydown="doSearch(arguments[0]||event)"   />
                </td>
            </tr>
            <tr >
                <td></td>
                <td class="control">
                    <input type="reset" name="btnReset" id="btnReset" value="Reset" />
                    <input type="submit" name="btnSubmit" id="btnSubmit" value="Search" />
                </td>
            </tr>
        </table>
    </fieldset>
</form>
<br />
<div id="content-placeholder">
    <p>JqGrid - Sample Search</p>
    <div id="jqgrid">
        <table id="grid"></table>
        <div id="pager"></div>
    </div>

    <div id="dialog" title="Feature not supported" style="display:none">
        <p>That feature is not supported.</p>
    </div>

    <div id="dialogSelectRow" title="Warning" style="display:none">
        <p>Please select row</p>
    </div>
</div>